import datetime
from rqdatac import *
import rqdatac as rq
import backtrader as bt
import pandas as pd

class myStrategy(bt.Strategy):
    def start(self):
        print("The world call me!")
    def prenext(self):
        print("Not mature")
    def nextstart(self):
        print("Rites of passage")
    def next(self):
        # print('A new bar')
        # print(self.data.close[0])
        # print(self.data.close[0],
        # self.data.close[-1],
        # self.data.close[-2])
        ma_value=sum([self.data.close[-cnt]for cnt in range(0,60)])/60
        if self.data.close[0]>ma_value and self.data.close[-1]<ma_value:
            self.order=self.buy()
            # print("long",self.data.datetime.date())
        if self.data.close[0] < ma_value and self.data.close[-1] > ma_value:
            self.order=self.sell()
            # print("short",self.data.datetime.date())

# 使用米筐获取螺纹钢主连合约日线行情数据
rq.init()
RB_data=rq.futures.get_dominant_price(underlying_symbols='RB', start_date=20200101, end_date=20250630, frequency='1d', fields=None, adjust_type='pre', adjust_method='prev_close_spread')
df=pd.DataFrame(RB_data)
df.to_csv('Pre_RB_data.csv')

# 1.create a cerebro
cerebro = bt.Cerebro()

#2.1 Create a datafeed using pandas
dataframe=pd.read_csv('Pre_RB_data.csv')
dataframe['date']=pd.to_datetime(dataframe['date'])
dataframe.set_index('date',inplace=True)
brf_daily=bt.feeds.PandasData(dataname=dataframe,
                              fromdate=datetime.datetime(2020,1,1),
                              todate=datetime.datetime(2025,6,30))

# 2.2add the data feed to Cerebro
cerebro.adddata(brf_daily)

# 3.add my strategy to cerebro
cerebro.addstrategy(myStrategy)

# 4.run
cerebro.run()

# 5. plot the result
cerebro.plot(style='candle')